<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\CompanyRequest;
use App\Model\Company;
use App\Model\Comsafeofficer;
use App\Model\Commanager;
use App\Model\Resident;
use App\Model\Tag;
use App\Model\TagRelation;
use App\User;
use Illuminate\Support\Facades\Auth;

use Validator;
use App\Services\UploadClass;
use Intervention\Image\ImageManagerStatic as Image;
use GuzzleHttp\Client;
use App\Services\ImageClass;
use Log;
use DB;
use Exception;


class SmallplaceController extends Controller
{
    /*创建公司*/
    public function create(Request $request)
    {
        // echo time();
        /*验证*/
        $validateRes = $this->validateAddCompany($request);
        if($validateRes['status']=='fail') {
            return response()->json(['message' => $validateRes['message'],'code'=>400],200);
        }
        
        /*无网络的时候上传图片*/
        $uploadImg = array();
        $uploadRes = $this->uploadCompanyPicture($request);
        
        if($uploadRes['status']=='fail') {
            return response()->json(['message' => $uploadRes['message'],'code'=>400],200);
        } else {
            if(!empty($uploadRes['returnImg'])) {
                $uploadImg = $uploadRes['returnImg'];
            }
        }
        
        $data = $request->all();
        
        $data = $this->filterAddCompanyFields($data);
        
        $company = $data;
        $company['address']=str_replace('null','',$company['address']);
        unset($company['safeofficer']);
        unset($company['commanager']);
       
        $company['tags']=$request->input('tags','');
        $tags=explode(',',$company['tags']);
        unset($company['tags']);
        
        if(!empty($uploadImg)) {
            foreach ($uploadImg as $key => $value) {
                $company[$key] = $value;
            }
        }
        /*生成公司定位图片*/
        $lng = $request->input('lng','');
        $lat = $request->input('lat','');
        // if(!empty($lng)&&!empty($lat)) {
        //     $imgclass = new ImageClass();
        //     $mapimg = $imgclass->maptoimg($lng,$lat,$company['comName']);
        //     $company['mapimg'] = $mapimg;
        // } else {
        //     $company['mapimg'] = '';
        // }
        
       
        $company['mapimg'] = '';
        $company['type'] = 2;
        $user = Auth::user();
        $company['userId'] = $user['id'];
        $safeofficer = isset($data['safeofficer'])?$data['safeofficer']:array();/*安全管理人员信息*/
        $commanager = isset($data['commanager'])?$data['commanager']:array();/*主要负责人员信息*/
        /*注册企业用户数据*/
        $insertUser = array();
        $insertUser['name'] = $company['comName'];
        if(isset($company['leaderPhone'])&&!empty($company['leaderPhone'])) {
            $insertUser['phone'] = $company['leaderPhone'];
        }
        
        /*获取企业首字母*/
        $comarr = preg_split('/(?<!^)(?!$)/u', $company['comName']);
        $comstr = '';
        // foreach ($comarr as $com){
        //     $comstr.= getFirstCharter($com);
        // }
        $insertUser['account'] = $company['idcard'];
        $insertUser['password'] = bcrypt('123456');
        $insertUser['type'] = 2;
        
        DB::beginTransaction();
		try {
			$id = Company::insertGetId($company);
			
		    if(!empty($id)) {
                /*安全管理人员*/
                foreach($safeofficer as $k=>$v) {
                    $safeofficer[$k]['companyId'] = $id;
                }
                $safeofficerObj = new Comsafeofficer();
                $safeofficeRes = $safeofficerObj->addAll($safeofficer);
                /*主要负责人员*/
                foreach($commanager as $k=>$v) {
                    $commanager[$k]['companyId'] = $id;
                }
                $commanagerObj = new Commanager();
                $commanagerRes = $commanagerObj->addAll($commanager);
                /*注册企业会员*/
                $insertUser['companyId'] = $id;
                $insertUser['created_at'] = date('Y-m-d H:i:s', time());
                $userId = User::insertGetId($insertUser);
                
                if(count($tags)>0){
                    // TagRelation::where('com_id',$id)->delete();
                    foreach($tags as $tag_id){
                        $rela=new TagRelation();
                        $rela->tag_id=$tag_id;
                        $rela->com_id=$id;
                        $rela->save();
                    }
                }
            }
            DB::commit(); 
		} catch(\Exception $e) {
		    echo json_encode($e->getMessage());
            DB::rollBack();
			return response()->json(['message' => '添加公司失败','code'=>400],200);
		} 
        return response()->json(['data' => $id,'message'=>'添加公司成功','code' => 200], 200);
    }

    /*更新公司*/
    public function update(Request $request)
    {
        /*验证公司信息*/
        $validateRes = $this->validateEditCompany($request);
        if($validateRes['status']=='fail') {
            return response()->json(['message' => $validateRes['message'],'code'=>400],200);
        } else {
            $company = $validateRes['company'];
        }
        /*无网络的时候上传图片*/
        $uploadImg = array();
        $uploadRes = $this->uploadCompanyPicture($request);
        if($uploadRes['status']=='fail') {
            return response()->json(['message' => $uploadRes['message'],'code'=>400],200);
        } else {
            if(!empty($uploadRes['returnImg'])) {
                $uploadImg = $uploadRes['returnImg'];
            }
        }
        $data = $request->all();
        $data = $this->filterEditCompanyFields($data);
        $companyData = $data;
        unset($companyData['safeofficer']);
        unset($companyData['commanager']);
        unset($companyData['id']);
        $safeofficer = isset($data['safeofficer'])?$data['safeofficer']:array();
        $commanager = isset($data['commanager'])?$data['commanager']:array();
        if(!empty($uploadImg)) {
            foreach ($uploadImg as $key => $value) {
                $companyData[$key] = $value;
            }
        }
        /*生成公司定位图片*/
        $lng = $request->input('lng','');
        $lat = $request->input('lat','');
        if(!empty($lng)&&!empty($lat)) {
            $imgclass = new ImageClass();
            $mapimg = $imgclass->maptoimg($lng,$lat,$company['comName']);
            $companyData['mapimg'] = $mapimg;
        }
        
        /*用户表更新*/
        $updateUser = array();
        $updateUser['state']=1;
        /*获取用户表*/
        $companyUser = User::where('companyId', $company['id'])->first();

        DB::beginTransaction();
        try {
            TagRelation::where('com_id',$company['id'])->delete();
            if(isset($companyData['tags'])){
                // $companyData['tags']=json_decode($companyData['tags'],1);
                $companyData['tags']=explode(',',$companyData['tags']);
            }
            if(isset($companyData['tags']) && count($companyData['tags'])>0){
                foreach($companyData['tags'] as $tag_id){
                    $rela=new TagRelation();
                    $rela->tag_id=$tag_id;
                    $rela->com_id=$company['id'];
                    $rela->save();
                }
            }
            unset($companyData['tags']);

            $companyRes = Company::where('id', $company['id'])->update($companyData);
            /*更新安全管理人员*/
            $this->updateComsafeofficer($company['id'], $safeofficer);
            /*更新主要负责人员*/
            $this->updateCommanager($company['id'], $commanager);
            /*更新用户*/
            if(!empty($companyUser)&&!empty($updateUser)) {
                $updateUser['updated_at'] = date('Y-m-d H:i:s', time());
                User::where('id', $companyUser['id'])->update($updateUser);
            }
            DB::commit();
        } catch(\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => '更新公司信息失败','code'=>400],200);
        }
        return response()->json(['data' => $company['id'],'message'=>'更新公司信息成功','code' => 200], 200);
    }
    public function tttt(){
        $tags=explode(',','8,9');
        dd($tags);
        $com=Company::with('userinfo')->findOrFail(165);
        if(!$com->userinfo){
            $comuser=[
                'name'=>$com->leader,
                'account'=>$com->idcard,
                'password'=>bcrypt('123456'),
                'type'=>3,
                'companyId'=>$com->id,
                'distinguish'=>'0',
                'province'=>$com->province,
                'city'=> $com->city,
                'district'=>$com->district,
                'street'=>$com->street,
                'community'=>$com->community
            ];
            $userid=User::insertGetId($comuser);
            Resident::where('com_id',$com->id)->delete();
            $resident=[
                'user_id'=>$userid,
                'com_id'=>$com->id
            ];
            Resident::insertGetId($resident);
        }else{
            $userid=$com->userinfo->id;
            $resi=Resident::where('user_id',$userid)->first();
            if(!$resi){
                $resident=[
                    'user_id'=>$userid,
                    'com_id'=>$com->id
                ];
                Resident::insertGetId($resident);
            }
        }
        $res=User::with(['cominfo'=>function($query){
            $query->select('id','leader','address','idcard','leaderPhone','lng','lat');
        },'resident'])->select('id','province','city','district','street','community','companyId')->where('id',$userid)->first();
        $res->resident->live_info=json_decode($res->resident->live_info);
        $res->resident->farm_info=json_decode($res->resident->farm_info);
        $res->resident->car_info=json_decode($res->resident->car_info);
        return response()->json(['data'=>$res,'message'=>'请求成功','code' => 200], 200);
    }
    /*更新公司  pc端 */
    public function update_pc(Request $request)
    {
        /*验证公司信息*/
        $validateRes = $this->validateEditCompany($request);
        if($validateRes['status']=='fail') {
            return redirect(url()->previous())->withErrors($validateRes['message']);
        } else {
            $company = $validateRes['company'];
        }

        $data = $request->all();
        // $data = $this->filterEditCompanyFields($data);
        $companyData = $data;
        unset($companyData['safeofficer_name']);
        unset($companyData['safeofficer_phone']);
        unset($companyData['safeofficer_wx']);
        unset($companyData['commanager_name']);
        unset($companyData['commanager_phone']);
        unset($companyData['commanager_wx']);
        unset($companyData['id']);
        unset($companyData['_token']);
        unset($companyData['file']);

        $safeofficer_name = isset($data['safeofficer_name'])?$data['safeofficer_name']:array();
        $safeofficer_phone = isset($data['safeofficer_phone'])?$data['safeofficer_phone']:array();
        $safeofficer_wx = isset($data['safeofficer_wx'])?$data['safeofficer_wx']:array();
        $commanager_name = isset($data['commanager_name'])?$data['commanager_name']:array();
        $commanager_phone = isset($data['commanager_phone'])?$data['commanager_phone']:array();
        $commanager_wx = isset($data['commanager_wx'])?$data['commanager_wx']:array();
        /*生成公司定位图片*/
        $lng = $request->input('lng','');
        $lat = $request->input('lat','');
        if(!empty($lng)&&!empty($lat)) {
            $imgclass = new ImageClass();
            $mapimg = $imgclass->maptoimg($lng,$lat,$company['comName']);
            $companyData['mapimg'] = $mapimg;
        }
        
        /*用户表更新*/
        $updateUser = array();
        $updateUser['state']=1;
        /*获取用户表*/
        $companyUser = User::where('companyId', $company['id'])->first();

        DB::beginTransaction();
        try {
            TagRelation::where('com_id',$company['id'])->delete();
            if(isset($companyData['tags']) && count($companyData['tags'])>0){
                foreach($companyData['tags'] as $tag_id){
                    $rela=new TagRelation();
                    $rela->tag_id=$tag_id;
                    $rela->com_id=$company['id'];
                    $rela->save();
                }
            }
            unset($companyData['tags']);
            $companyRes = Company::where('id', $company['id'])->update($companyData);
            /*更新安全管理人员*/
            $this->updateComsafeofficer2($company['id'], $safeofficer_name,$safeofficer_phone,$safeofficer_wx);
            /*更新主要负责人员*/
            $this->updateCommanager2($company['id'], $commanager_name,$commanager_phone,$commanager_wx);
            /*更新用户*/
            if(!empty($companyUser)&&!empty($updateUser)) {
                $updateUser['updated_at'] = date('Y-m-d H:i:s', time());
                User::where('id', $companyUser['id'])->update($updateUser);
            }
            DB::commit(); 
        } catch(\Exception $e) {
            dd($e);
            DB::rollBack();
            return redirect(url()->previous())->withErrors('更新公司信息失败');
        }
        return redirect(route('admin.company.comlist1'))->with(['status'=>'修改成功']);
    }
    /*获取公司信息*/
    public function getCompany(Request $request)
    {
        $id = $request->input('id');
        if(empty($id)) {
            return response()->json(['message'=>'参数错误','code' => 400], 200);
        }
        $returnData = array();
        $filed = $this->getCompanyReturnField();
        $company = Company::where('id', $id)->first($filed);
        if(!empty($company)) {
            /*获取安全管理人员*/
            $safeofficer_field = array('id', 'companyId', 'name', 'phone');
            $safeofficer = Comsafeofficer::where('companyId', $company['id'])->get($safeofficer_field);
            $safeofficer = json_decode(json_encode($safeofficer), true);
            /*获取主要负责人员*/
            $commanager_field = array('id', 'companyId', 'name', 'phone','wx');
            $commanager = Commanager::where('companyId', $company['id'])->get($commanager_field);
            $commanager = json_decode(json_encode($commanager), true);

            $returnData = $company;
            $returnData['safeofficer'] = $safeofficer;
            $returnData['commanager'] = $commanager;
            $returnData['tags']=json_encode(Tag::get());
            $returnData['tagrelations']=json_encode(TagRelation::where('com_id',$company['id'])->pluck('tag_id')->toArray());
            return response()->json(['data' => $returnData,'message'=>'返回公司信息成功','code' => 200], 200);
        } else {
            return response()->json(['message'=>'公司不存在','code' => 404], 200);
        }
    }

    protected function getCompanyReturnField()
    {
        $field = array('id','comName', 'province', 'city', 'district', 'street', 'community', 'address', 'postcode', 'leader','leaderPhone','accompany','workersNum','area', 'service',/*'material','product','assets','income',*/'space',/*'electrician','weld','highwork','refrigeration','else','boiler','kongyaji','qiping','ylgd','elevator','qzjx','jdcl',*/'yhqgpfifteen','yhqgpfifty','trqgd','cjrl','photo','license','lat','lng','idcard');
        return $field;
    }

    /*更新安全管理人员*/
    protected function updateComsafeofficer($companyId, $safeofficer)
    {
        /*安全管理人员*/
        $old_safeofficer = Comsafeofficer::where('companyId', $companyId)->get();
        $old_safeofficer = json_decode(json_encode($old_safeofficer), true);
        $insert_safeofficer = array();
        $update_safeofficer = array();
        $delete_safeofficer = array();
        foreach($safeofficer as $k=>$v) {/*安全管理人员处理数据*/
            $flag = 1;/*安全管理人员插入标志*/
            $update_data = array();
            foreach($old_safeofficer as $key=>$val) {
                if(isset($v['id'])&&($v['id']==$val['id'])) {
                    $flag = 0;
                    $update_data = $v;
                }
            }
            if($flag==1) {
                $insert_safeofficer[] = $v;
            } else {
                $update_safeofficer[] = $update_data;
            }
        }
        /*安全管理人员删除ids*/
        $newsafeofficer_ids = array_column($safeofficer, 'id');
        foreach($old_safeofficer as $k=>$v) {
            $delete_flag = 1;
            foreach ($newsafeofficer_ids as $key => $value) {
                if($v['id']==$value) {
                    $delete_flag = 0;
                }
            }
            if($delete_flag==1) {
                $delete_safeofficer[] = $v;
            }
        }
        $delete_safeofficer_ids = array_column($delete_safeofficer, "id");
        try{
            /*安全管理人员批量添加*/
            $comsafeofficerObj = new Comsafeofficer();
            if(!empty($insert_safeofficer)) {
                foreach ($insert_safeofficer as $key => $value) {
                    $insert_safeofficer[$key]['companyId'] = $companyId;
                }
                $comsafeofficerObj->addAll($insert_safeofficer);
            }
            /*安全管理人员批量更新*/
            if(!empty($update_safeofficer)) {
                $comsafeofficerObj->updateAll($update_safeofficer);
            }
            /*安全管理人员批量删除*/
            if(!empty($delete_safeofficer_ids)) {
                Comsafeofficer::whereIn('id', $delete_safeofficer_ids)->delete();
            }
            return array('status'=>'success');
        } catch(Exception $e) {
            return array('status'=>'fail', 'message'=> $e->getMessage());
        }
        
    }
    /*更新安全管理人员*/
    protected function updateComsafeofficer2($companyId, $namearr,$phonearr,$wxarr)
    {
        try{
            Comsafeofficer::where('companyId', $companyId)->delete();
            $arr=[];
            foreach ($namearr as $k => $v) {
                $arr[]=[
                    'companyId'=>$companyId,
                    'name'=>$namearr[$k],
                    'phone'=>$phonearr[$k],
                    'wx'=>$wxarr[$k]
                ];
            }
            if($arr) {
                Comsafeofficer::insert($arr);
            }
            return array('status'=>'success');
        } catch(Exception $e) {
            return array('status'=>'fail', 'message'=> $e->getMessage());
        }
        
    }
    /*更新安全管理人员*/
    protected function updateCommanager2($companyId, $namearr,$phonearr,$wxarr)
    {
        try{
            Commanager::where('companyId', $companyId)->delete();
            $arr=[];
            foreach ($namearr as $k => $v) {
                $arr[]=[
                    'companyId'=>$companyId,
                    'name'=>$namearr[$k],
                    'phone'=>$phonearr[$k],
                    'wx'=>$wxarr[$k]
                ];
            }
            if($arr) {
                Commanager::insert($arr);
            }
            return array('status'=>'success');
        } catch(Exception $e) {
            return array('status'=>'fail', 'message'=> $e->getMessage());
        }
        
    }
    /*更新主要负责人员*/
    protected function updateCommanager($companyId, $commanager)
    {
        /*主要负责人员*/
        $old_commanager = Commanager::where('companyId', $companyId)->get();
        $old_commanager = json_decode(json_encode($old_commanager), true);
        $insert_commanager = array();
        $update_commanager = array();
        $delete_commanager = array();
        foreach($commanager as $k=>$v) {/*安全管理人员处理数据*/
            $flag = 1;/*安全管理人员插入标志*/
            $update_data = array();
            foreach($old_commanager as $key=>$val) {
                if(isset($v['id'])&&($v['id']==$val['id'])) {
                    $flag = 0;
                    $update_data = $v;
                }
            }
            if($flag==1) {
                $insert_commanager[] = $v;
            } else {
                $update_commanager[] = $update_data;
            }
        }
        /*安全管理人员删除ids*/
        $newcommanager_ids = array_column($commanager, 'id');
        foreach($old_commanager as $k=>$v) {
            $delete_flag = 1;
            foreach ($newcommanager_ids as $key => $value) {
                if($v['id']==$value) {
                    $delete_flag = 0;
                }
            }
            if($delete_flag==1) {
                $delete_commanager[] = $v;
            }
        }
        $delete_commanager_ids = array_column($delete_commanager, "id");
        try{
           /*安全管理人员批量添加*/
            $commanagerObj = new Commanager();
            if(!empty($insert_commanager)) {
                foreach ($insert_commanager as $key => $value) {
                    $insert_commanager[$key]['companyId'] = $companyId;
                }
                $commanagerObj->addAll($insert_commanager);
            }
            /*安全管理人员批量更新*/
            if(!empty($update_commanager)) {
                $commanagerObj->updateAll($update_commanager);
            }
            /*安全管理人员批量删除*/
            if(!empty($delete_commanager_ids)) {
                Commanager::whereIn('id', $delete_commanager_ids)->delete();
            } 
            return array('status'=>'success');
        } catch(Exception $e) {
            return array('status'=>'fail', 'message'=> $e->getMessage());
        }
        
    }
    /*添加公司验证*/
    protected function validateAddCompany(Request $request)
    {   
        $rules = [
            'comName' => 'required|max:240',
            'province' => 'required',
            'city' => 'required',
            'district' => 'required',
            'street' => 'required',
            'community' => 'required',
            'address' =>'required|max:100',
            'postcode' => 'nullable|regex:/^[0-9]{6}$/',
            'leader' => 'required|max:20',
            //'leaderPhone' => 'nullable|regex:/^1[34578]\d{9}$/',
            'area' => 'required|max:255',
            'service' => 'nullable|max:255',
            'accompany' => 'required|max:240',
            'workersNum' => 'required|integer|min:0',
            'enterprise'=>'required',
            'idcard'=>'required',
            //'material' => 'max:255',
            //'product' => 'max:255',
            //'assets' => 'max:255',
            //'income' => 'numeric|min:0',
            'space' => 'required|numeric|min:0',
            //'electrician' => 'integer|between:1,2',
            //'weld' => 'integer|between:1,2',
            //'highwork' => 'integer|between:1,2',
            //'refrigeration' => 'integer|between:1,2',
            //'else' => 'max:255',
            //'boiler' => 'integer|min:0',
            //'kongyaji' => 'integer|min:0',
            //'qiping' => 'integer|min:0',
            //'ylgd' => 'integer|min:0',
            //'elevator' => 'integer|min:0',
            //'qzjx' => 'integer|min:0',
            //'jdcl' => 'integer|min:0',
            'yhqgpfifteen' => 'integer|min:0',
            'yhqgpfifty' => 'integer|min:0',
            'trqgd' => 'integer|between:1,2',
            'cjrl' => 'integer|between:1,2',
            // 'photo' => 'required',
            // 'license' => 'required',
            'categoryId' => 'required|integer|min:1'
        ];
        $message = [
        	'enterprise.required'=>'企业类别不能为空',
            'idcard.required'=>'营业执照号不能为空',
            'comName.required' => '公司名称不能为空',
            'comName.max' => '公司名称长度不能超过240个字符',
            'province.required' => '请选择省份',
            'city.required' => '请选择城市',
            'district.required' => '请选择区',
            'street.required' => '请选择街道',
            'community.required' => '请选择社区',
            'address.required' => '请输入街道、门牌号等信息',
            'address.max' => '街道、门牌号等信息长度不能超过100个字符',
            'postcode.regex' => '邮政编码必须是六位数字',
            'leader.required' => '法人姓名不能为空',
            'leader.max' => '法人姓名不能超过20个字符',
            //'leaderPhone.regex'=>'法定代表人电话格式不正确',
            'area.required'=>'建筑面积不能为空',
            'area.max'=>'建筑面积不能超过255个字符',
            'service.max'=>'技术服务机构人员不能超过255个字符',
            'accompany.required'=>'企业陪同人员不能为空',
            'accompany.max' => '企业陪同人员不能超过240个字符',
            'workersNum.required' => '员工人数不能为空',
            'workersNum.integer' => '员工人数必须是数字',
            'workersNum.min' => '员工人数最小是0',
            // 'material.max' => '主要原料长度不能超过255个字符',
            // 'product.max' => '主要产品长度不能超过255个字符',
            // 'assets.max' => '固定资产长度不能超过255个字符',
            // 'income.numeric' => '收入必须是数字',
            // 'income.min' => '收入最少是0',
            'space.required' => '占地面积不能为空',
            'space.numeric' => '占地面积必须是数字',
            'space.min' => '占地面积最小是0',
            // 'electrician.integer' => '电工作业传递参数不正确',
            // 'electrician.between' => '电工作业传递参数不正确',
            // 'weld.integer' => '焊接与热切割作业传递参数不正确',
            // 'weld.between' => '焊接与热切割作业传递参数不正确',
            // 'highwork.integer' => '高处作业传递参数不正确',
            // 'highwork.between' => '高处作业传递参数不正确',
            // 'refrigeration.integer' => '制冷与空调传递参数不正确',
            // 'refrigeration.between' => '制冷与空调传递参数不正确',
            // 'else.max' => '其它长度不能超过255个字符',
            // 'boiler.integer' => '锅炉参数不正确',
            // 'boiler.min' => '锅炉数量最小为0',
            // 'kongyaji.integer' => '空压机参数不正确',
            // 'kongyaji.min' => '空压机数量最小为0',
            // 'qiping.integer' => '气瓶参数不正确',
            // 'qiping.min' => '气瓶数量最小为0',
            // 'ylgd.integer' => '压力管道参数不正确',
            // 'ylgd.min' => '压力数量最小为0',
            // 'elevator.integer' => '电梯参数不正确',
            // 'elevator.min' => '电梯数量最小为0',
            // 'qzjx.integer' => '起重机械参数不正确',
            // 'qzjx.min' => '起重机械数量最小为0',
            // 'jdcl.integer' => '场(厂)内专用机动车辆参数不正确',
            // 'jdcl.min' => '场(厂)内专用机动车辆数量最小为0',
            'yhqgpfifteen.integer' => '液化气钢瓶15kg数量参数不正确',
            'yhqgpfifteen.min' => '液化气钢瓶15kg数量最小为0',
            'yhqgpfifty.integer' => '液化气钢瓶50kg数量参数不正确',
            'yhqgpfifty.min' => '液化气钢瓶50kg数量最小为0',
            'trqgd.integer' => '天然气管道传递参数不正确',
            'trqgd.between' => '天然气管道传递参数不正确',
            'cjrl.integer' => '醇基燃料传递参数不正确',
            'cjrl.between' => '醇基燃料传递参数不正确',
            // 'photo.required' => '门头照片不能为空',
            // 'license.required' => '营业执照不能为空',
            'categoryId.required' => '分类id不能为空',
            'categoryId.integer' => '分类参数不正确',
            'categoryId.min' => '分类参数不正确',
        ];
        $validator = Validator::make($request->all(), $rules, $message);
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return array('status'=>'fail', 'message'=>$error);
        }
        $data = $request->all();
        /*验证安全管理人员*/
        $comsafeofficer = isset($data['safeofficer'])?$data['safeofficer']:array();
        if(!empty($comsafeofficer)) {
            foreach($comsafeofficer as $k=>$v) {
                if(empty($v['name'])||empty($v['phone'])) {
                    return array('status'=>'fail', 'message'=>'安全管理人员信息不全面');
                }
            }
        }
        /*验证主要负责人*/
        $commanager = isset($data['commanager'])?$data['commanager']:array();
        if(!empty($commanager)) {
            foreach($commanager as $k=>$v) {
                if(empty($v['name'])||empty($v['phone'])||empty($v['wx'])) {
                    return array('status'=>'fail', 'message'=>'主要负责人员信息不全面');
                }
            }
        }
        /*验证公司名称是否已经存在*/
        $company_has = Company::where('comName', $data['comName'])->first(['id']);
        if(!empty($company_has)) {
            return array('status'=>'fail', 'message'=>'公司信息已经存在');
        }
        

        return array('status'=>'success', 'message'=>'验证成功');
    }

    protected function validateEditCompany(Request $request)
    {
        $rules = [
            'id' => 'required',
            'comName' => 'required|max:240',
            'province' => 'required',
            'city' => 'required',
            'district' => 'required',
            'street' => 'required',
            'community' => 'required',
            'address' =>'required|max:100',
            'postcode' => 'nullable|regex:/^[0-9]{6}$/',
            'leader' => 'required|max:20',
            //'leaderPhone' => 'nullable|regex:/^1[34578]\d{9}$/',
            'area' => 'required|max:255',
            // 'service' => 'nullable|max:255',
            // 'accompany' => 'required|max:240',
            // 'workersNum' => 'required|integer|min:0', 
            // 
            /*'material' => 'max:255',
            'product' => 'max:255',
            'assets' => 'max:255',
            'income' => 'numeric|min:0',*/
            'space' => 'required|numeric|min:0',
            /*'electrician' => 'integer|between:1,2',
            'weld' => 'integer|between:1,2',
            'highwork' => 'integer|between:1,2',
            'refrigeration' => 'integer|between:1,2',
            'else' => 'max:255',
            'boiler' => 'integer|min:0',
            'kongyaji' => 'integer|min:0',
            'qiping' => 'integer|min:0',
            'ylgd' => 'integer|min:0',
            'elevator' => 'integer|min:0',
            'qzjx' => 'integer|min:0',
            'jdcl' => 'integer|min:0',*/
            'yhqgpfifteen' => 'integer|min:0',
            'yhqgpfifty' => 'integer|min:0',
            'trqgd' => 'integer|between:1,2',
            'cjrl' => 'integer|between:1,2',
            // 'photo' => 'required',
            // 'license' => 'required',
        ];
        $message = [
            'id.required' => 'id不能为空',
            'comName.required' => '公司名称不能为空',
            'comName.max' => '公司名称长度不能超过240个字符',
            'province.required' => '请选择省份',
            'city.required' => '请选择城市',
            'district.required' => '请选择区',
            'street.required' => '请选择街道',
            'community.required' => '请选择社区',
            'address.required' => '请输入街道、门牌号等信息',
            'address.max' => '街道、门牌号等信息长度不能超过100个字符',
            'postcode.regex' => '邮政编码必须是六位数字',
            'leader.required' => '法人姓名不能为空',
            'leader.max' => '法人姓名不能超过20个字符',
            //'leaderPhone.regex'=>'法定代表人电话格式不正确',
            'area.required'=>'建筑面积不能为空',
            'area.max'=>'建筑面积不能超过255个字符',
            'service.max'=>'技术服务机构人员不能超过255个字符',
            'accompany.required'=>'企业陪同人员不能为空',
            'accompany.max' => '企业陪同人员不能超过240个字符',
            'workersNum.required' => '员工人数不能为空',
            'workersNum.integer' => '员工人数必须是数字',
            'workersNum.min' => '员工人数最小是0',
            /*'material.max' => '主要原料长度不能超过255个字符',
            'product.max' => '主要产品长度不能超过255个字符',
            'assets.max' => '固定资产长度不能超过255个字符',
            'income.numeric' => '收入必须是数字',
            'income.min' => '收入最少是0',*/
            'space.required' => '占地面积不能为空',
            'space.numeric' => '占地面积必须是数字',
            'space.min' => '占地面积最小是0',
            /*'electrician.integer' => '电工作业传递参数不正确',
            'electrician.between' => '电工作业传递参数不正确',
            'weld.integer' => '焊接与热切割作业传递参数不正确',
            'weld.between' => '焊接与热切割作业传递参数不正确',
            'highwork.integer' => '高处作业传递参数不正确',
            'highwork.between' => '高处作业传递参数不正确',
            'refrigeration.integer' => '制冷与空调传递参数不正确',
            'refrigeration.between' => '制冷与空调传递参数不正确',
            'else.max' => '其它长度不能超过255个字符',
            'boiler.integer' => '锅炉参数不正确',
            'boiler.min' => '锅炉数量最小为0',
            'kongyaji.integer' => '空压机参数不正确',
            'kongyaji.min' => '空压机数量最小为0',
            'qiping.integer' => '气瓶参数不正确',
            'qiping.min' => '气瓶数量最小为0',
            'ylgd.integer' => '压力管道参数不正确',
            'ylgd.min' => '压力数量最小为0',
            'elevator.integer' => '电梯参数不正确',
            'elevator.min' => '电梯数量最小为0',
            'qzjx.integer' => '起重机械参数不正确',
            'qzjx.min' => '起重机械数量最小为0',
            'jdcl.integer' => '场(厂)内专用机动车辆参数不正确',
            'jdcl.min' => '场(厂)内专用机动车辆数量最小为0',*/
            'yhqgpfifteen.integer' => '液化气钢瓶15kg数量参数不正确',
            'yhqgpfifteen.min' => '液化气钢瓶15kg数量最小为0',
            'yhqgpfifty.integer' => '液化气钢瓶50kg数量参数不正确',
            'yhqgpfifty.min' => '液化气钢瓶50kg数量最小为0',
            'trqgd.integer' => '天然气管道传递参数不正确',
            'trqgd.between' => '天然气管道传递参数不正确',
            'cjrl.integer' => '醇基燃料传递参数不正确',
            'cjrl.between' => '醇基燃料传递参数不正确',
            // 'photo.required' => '门头照片不能为空',
            // 'license.required' => '营业执照不能为空',
        ];
        $validator = Validator::make($request->all(), $rules, $message);
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return array('status'=>'fail', 'message'=>$error);
        }
        $data = $request->all();
        /*验证公司是否存在*/
        $company = Company::where('id', $data['id'])->first();
        if(empty($company)) {
            return array('status'=>'fail', 'message'=>'公司不存在');
        }
        /*验证安全管理人员*/
        $comsafeofficer = isset($data['safeofficer'])?$data['safeofficer']:array();
        if(!empty($comsafeofficer)) {
            foreach($comsafeofficer as $k=>$v) {
                if(empty($v['name'])||empty($v['phone'])) {
                    return array('status'=>'fail', 'message'=>'安全管理人员信息不全面');
                }
            }
        } 
        /*验证主要负责人*/
        $commanager = isset($data['commanager'])?$data['commanager']:array();
        if(!empty($commanager)) {
            foreach($commanager as $k=>$v) {
                if(empty($v['name'])||empty($v['phone'])||empty($v['wx'])) {
                    return array('status'=>'fail', 'message'=>'主要负责人员信息不全面');
                }
            }
        }
        /*验证公司名称是否已经存在*/
        $company_has = Company::where('comName', $data['comName'])->first(['id']);
        if(!empty($company_has)&&$company_has['id']!=$company['id']) {
            return array('status'=>'fail', 'message'=>'公司信息已经存在');
        }
        

        return array('status'=>'success', 'message'=>'验证成功', 'company'=>$company);
    }

    protected function filterAddCompanyFields($data)
    {
        $allowFields = array('comName', 'province', 'city', 'district', 'street', 'address', 'community', 'postcode', 'leader', 'leaderPhone', 'area', 'service','accompany', 'workersNum','tags', 'idcard',/*'material', 'product', 'assets', 'income',*/ 'space', /*'electrician', 'weld', 'highwork', 'refrigeration', 'else', 'boiler', 'kongyaji', 'qiping', 'ylgd', 'elevator', 'qzjx', 'jdcl',*/ 'yhqgpfifteen', 'yhqgpfifty', 'trqgd', 'cjrl', 'photo', 'license','categoryId','lat','lng','enterprise');
        $allowFieldsArr = array('safeofficer'=>array('name', 'phone'), 'commanager'=>array('name', 'phone', 'wx'));
        $returnData = filterAllowFields($allowFields, $data);
        foreach($allowFieldsArr as $k=>$v) {
            if(isset($data[$k])) {
                foreach($data[$k] as $key=>$val) {
                    $returnData[$k][] = filterAllowFields($v, $val);
                }
            }
        }
        return $returnData;
    }

    protected function filterEditCompanyFields($data)
    {
        $allowFields = array('id','comName', 'province', 'city', 'district', 'street', 'address', 'community', 'postcode', 'leader', 'leaderPhone', 'area', 'service', 'accompany', 'workersNum', 'tags',/*'material', 'product', 'assets', 'income',*/ 'space',/*'electrician', 'weld', 'highwork', 'refrigeration', 'else', 'boiler', 'kongyaji', 'qiping', 'ylgd', 'elevator', 'qzjx', 'jdcl',*/ 'yhqgpfifteen', 'yhqgpfifty', 'trqgd', 'cjrl', 'photo', 'license','lat','lng');
        $allowFieldsArr = array('safeofficer'=>array('id', 'name', 'phone'), 'commanager'=>array('id', 'name', 'phone', 'wx'));

        $returnData = filterAllowFields($allowFields, $data);
        foreach($allowFieldsArr as $k=>$v) {
            if(isset($data[$k])) {
                foreach($data[$k] as $key=>$val) {
                    $returnData[$k][] = filterAllowFields($v, $val);
                }
            }
        }
        return $returnData;
    }

    protected function uploadCompanyPicture(Request $request)
    {
        $photo = $request->file("photo","");
        $license = $request->file("license","");
        $returnImg = array();
        $imgArr = array();
        if($request->hasFile("photo")&&$photo->isValid()) {
            $imgArr['photo'] = $photo;
        }

        if($request->hasFile("license")&&$license->isValid()) {
            $imgArr['license'] = $license;
        }

        if(!empty($imgArr)) {
            foreach($imgArr as $key=>$val) {
                $upload = new UploadClass(); 
                $upload->exts=array('jpg','png'); 
                $upload->maxSize=5*1024*1024; 
                $upload->savePath='storage/images'; 

                $imgUrl = $upload->upload($val); 
                
                if($imgUrl) {
                    // $host = $_SERVER['HTTP_HOST'];
                    // $host = '10.100.202.114:30001';
                    // // $host = $_SERVER['HTTP_HOST'];
                    // $client = new \GuzzleHttp\Client();
                    // $avatarResponse = $client->get('http://'.$host.$imgUrl);
                    // $img = Image::make($avatarResponse->getBody()->getContents())->resize(800, 600);
                    $newimg = substr($imgUrl,1);
                    $img = Image::make($newimg)->resize(800, 600);
                    
                    $newimgUrl = str_replace(".","_43.",$newimg);
                    $img->save($newimgUrl);
                    $returnImg[$key] = $imgUrl;
                } else {
                    $message = $upload->getError();  
                    return array('status'=>'fail', 'message'=>$message);
                }
            }
        }
        
        return array('status'=>'success', 'message'=>'上传成功', 'returnImg'=>$returnImg);
        
    }
    public function uploadcompic(Request $request){
        $upload = new UploadClass(); 
        $upload->exts=array('jpg','png'); 
        $upload->maxSize=5*1024*1024; 
        $upload->savePath='storage/images'; 
        $file = $request->file('file');
        $imgUrl = $upload->upload($file); 
        if($imgUrl) {
            $host = $_SERVER['HTTP_HOST'];
            $client = new \GuzzleHttp\Client();
            $avatarResponse = $client->get('http://'.$host.$imgUrl);
            $img = Image::make($avatarResponse->getBody()->getContents())->resize(800, 600);
            $newimg = substr($imgUrl,1);
            $newimgUrl = str_replace(".","_43.",$newimg);
            $img->save($newimgUrl);
            return array('status'=>'success', 'message'=>'上传成功', 'returnImg'=>$imgUrl);
        } else {
            $message = $upload->getError();  
            return array('status'=>'fail', 'message'=>$message);
        }
    }
    public function gupdate(Request $request){
    	$data = $request->all();
        $rules = [
        	'name'=> 'required',
        	//'phone'=> 'required',
        	'email'=> 'required',
        	'sex'=> 'required',
            'card_front'  => 'required',
            'card_behind'  => 'required',
            //'ramarks'=>'required'

        ];
        $message = [
        			'name.required'  => '名称不能为空',
        			//'phone.required'  => '手机号码不能为空',
        			'email.required'  => '邮箱不能为空',
        			'sex.required'  => '性别不能为空',
                    'card_front.required'  => '身份证正面照片不能为空',
                   	'card_behind.required'  => '身份证反面照片不能为空'

                ];
        $validator = Validator::make($data,$rules,$message);
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return response()->json(['message' => $error,'code'=>400],200);
        }
        $u = Auth::user();
		$user['name']=$request->input("name");
		$user['phone']=$request->input("phone");
		$user['email']=$request->input("email");
		$user['sex']=$request->input("sex");
		$userr = User::where('name',$user['name'])->first();
        if($userr){
        	return response()->json(['message' => '名称已存在','code'=>400],200);
        }
        $userz = User::where('phone',$user['phone'])->first();
        if($userz){
        	return response()->json(['message' => '号码已存在','code'=>400],200);
        }
		$uploadImg = array();
        $uploadRes = $this->uploadGrPicture($request);
        if($uploadRes['status']=='fail') {
            return response()->json(['message' => $uploadRes['message'],'code'=>400],200);
        } else {
            if(!empty($uploadRes['returnImg'])) {
                $uploadImg = $uploadRes['returnImg'];
            }
        }
        $user['card_front']=$uploadImg['photo'];
        $user['card_behind']=$uploadImg['license'];
        $user['state']=1;
       	$z = User::where('id', $u['id'])->update($user);
       	if($z){
       		$user = User::where('id',$u['id'])->first();
       		return response()->json(['data' =>$user,'message'=>'更新个人信息成功','code' => 200], 200);
       	}else{
       		return response()->json(['message' => '更新失败','code'=>400],200);
       	}
		
    }
    
    protected function uploadGrPicture(Request $request)
    {
        $photo = $request->file("card_front","");
        $license = $request->file("card_behind","");
        $returnImg = array();
        $imgArr = array();
        if($request->hasFile("card_front")&&$photo->isValid()) {
            $imgArr['photo'] = $photo;
        }

        if($request->hasFile("card_behind")&&$license->isValid()) {
            $imgArr['license'] = $license;
        }

        if(!empty($imgArr)) {
         
            foreach($imgArr as $key=>$val) {
                $upload = new UploadClass(); 
                $upload->exts=array('jpg','png'); 
                $upload->maxSize=5*1024*1024; 
                $upload->savePath='storage/images'; 

                $imgUrl = $upload->upload($val); 
                if($imgUrl) {
                    // $host = $_SERVER['HTTP_HOST'];
                    
                    // $client = new \GuzzleHttp\Client();
                    
                    // $avatarResponse = $client->get('http://'.$host.$imgUrl);
                    // $img = Image::make($avatarResponse->getBody()->getContents())->resize(800, 600);
                    // $newimg = substr($imgUrl,1);
                    // $newimgUrl = str_replace(".","_43.",$newimg);
                    // $img->save($newimgUrl);
                    $returnImg[$key] = $imgUrl;
                } else {
                    $message = $upload->getError();  
                    return array('status'=>'fail', 'message'=>$message);
                }
            }
        }
        return array('status'=>'success', 'message'=>'上传成功', 'returnImg'=>$returnImg);
    }
    // 创建住户
    public function household(Request $request){
    	$data = $request->all();
        $rules = [
        	'leader' => 'required|max:240',
        	'province' => 'required',
            'city' => 'required',
            'district' => 'required',
            'street' => 'required',
            'community' => 'required',
            'address' =>'required|max:100',
            'idcard'=>'required',
            'door_code'=>'required',
            'birthday'=>'required',
            'live_people'=>'required',
            'live_info'=>'required',
            'live_type'=>'required',
            'old_type'=>'required',
            'fire_type'=>'required',
            'farm_num'=>'required',
            'farm_info'=>'required',
            'car_info'=>'required'
        ];
        $message = [
        	'leader.required' => '户主名称不能为空',
            'leader.max' => '户主名称长度不能超过240个字符',
            'province.required' => '请选择省份',
            'city.required' => '请选择城市',
            'district.required' => '请选择区',
            'street.required' => '请选择街道',
            'community.required' => '请选择社区',
            'address.required' => '请输入街道、门牌号等信息',
            'address.max' => '街道、门牌号等信息长度不能超过100个字符',
            'idcard.required'=>'身份证号不能为空',
            'door_code.required'=>'门牌号不能为空',
            'birthday.required'=>'出生年月不能为空',
            'live_people.required'=>'居住人数不能为空',
            'live_info.required'=>'同住人信息不能为空',
            'live_type.required'=>'住户类型不能为空',
            'old_type.required'=>'老人类型不能为空',
            'fire_type.required'=>'燃气类型不能为空',
            'farm_num.required'=>'农田数不能为空',
            'farm_info.required'=>'牲畜情况不能为空',
            'car_info.required'=>'车辆情况不能为空'
        ];
        $validator = Validator::make($data,$rules,$message);
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return response()->json(['message' => $error,'code'=>400],200);
        }
        DB::beginTransaction();
        try {
            $u = Auth::user();
            $company=[
                'comName' => $request->input("leader"),
                'leader' => $request->input("leader"),
                'leaderPhone' => $request->input("leaderPhone"),
                'province' => $request->input("province"),
                'city' => $request->input("city"),
                'district' => $request->input("district"),
                'street' => $request->input("street"),
                'community' => $request->input("community"),
                'address' => $request->input("address"),
                'area'=>$request->input("live_area"),
                'idcard' => $request->input("idcard"),
                'lng'=> $request->input("lng"),
                'lat'=> $request->input("lat"),
                'userId' => $u->id,
                'enterprise' => 3,
                'categoryId' => 12,
                'type' => 2,
            ];
            
            $com_id = Company::insertGetId($company);

            $comuser=[
                'name'=>$company['leader'],
                'account'=>$company['idcard'],
                'password'=>bcrypt('123456'),
                'type'=>3,
                'companyId'=>$com_id,
                'distinguish'=>'0',
                'province'=>$company['province'],
                'city'=> $company['city'],
                'district'=>$company['district'],
                'street'=>$company['street'] ,
                'community'=>$company['community']
            ];
            $user_id=User::insertGetId($comuser);
            $resident=[
                'user_id'=>$user_id,
                'com_id'=>$com_id,
                'door_code'=>$request->input('door_code'),
                'birthday'=>$request->input('birthday'),
                'live_area'=>$request->input('live_area'),
                'live_people'=>$request->input('live_people'),
                'live_info'=>$request->input('live_info'),
                'live_type'=>$request->input('live_type'),
                'old_type'=>$request->input('old_type'),
                'fire_type'=>$request->input('fire_type'),
                'warm_type'=>$request->input('warm_type')??null,
                'alarm_type'=>$request->input('alarm_type')??null,
                'fire5_num1'=>$request->input('fire5_num1')??null,
                'fire5_num2'=>$request->input('fire5_num2')??null,
                'fire15_num1'=>$request->input('fire15_num1')??null,
                'fire15_num2'=>$request->input('fire15_num2')??null,
                'fire50_num1'=>$request->input('fire50_num1')??null,
                'fire50_num2'=>$request->input('fire50_num2')??null,
                'farm_num'=>$request->input('farm_num'),
                'farm_info'=>$request->input('farm_info'),
                'car_info'=>$request->input('car_info'),
                'note'=>$request->input('note')
            ];
            Resident::insertGetId($resident);
            DB::commit();
            return response()->json(['message'=>'创建成功','code' => 200], 200);
        } catch(Exception $e) {
            DB::rollBack();
            return response()->json(['message' =>$e->getMessage(),'code'=>400],200);
        }
    }
    public function getresidentinfo(Request $request){
        $com=Company::with('userinfo')->findOrFail($request->input('id'));
        if(!$com->userinfo){
            $comuser=[
                'name'=>$com->leader,
                'account'=>$com->idcard,
                'password'=>bcrypt('123456'),
                'type'=>3,
                'companyId'=>$com->id,
                'distinguish'=>'0',
                'province'=>$com->province,
                'city'=> $com->city,
                'district'=>$com->district,
                'street'=>$com->street,
                'community'=>$com->community
            ];
            $userid=User::insertGetId($comuser);
            Resident::where('com_id',$com->id)->delete();
            $resident=[
                'user_id'=>$userid,
                'com_id'=>$com->id
            ];
            Resident::insertGetId($resident);
        }else{
            $userid=$com->userinfo->id;
            $resi=Resident::where('user_id',$userid)->first();
            if(!$resi){
                $resident=[
                    'user_id'=>$userid,
                    'com_id'=>$com->id
                ];
                Resident::insertGetId($resident);
            }
        }
        $res=User::with(['cominfo'=>function($query){
            $query->select('id','leader','address','idcard','leaderPhone','lng','lat');
        },'resident'])->select('id','province','city','district','street','community','companyId')->where('id',$userid)->first();
        $res->resident->live_info=json_decode($res->resident->live_info);
        $res->resident->farm_info=json_decode($res->resident->farm_info);
        $res->resident->car_info=json_decode($res->resident->car_info);
        return response()->json(['data'=>$res,'message'=>'请求成功','code' => 200], 200);
    }
    public function uphousehold(Request $request){
    	$data = $request->all();
        $rules = [
            'user_id'=>'required',
            'leader' => 'required|max:240',
            'province' => 'required',
            'city' => 'required',
            'district' => 'required',
            'street' => 'required',
            'address' =>'required|max:100',
            'idcard'=>'required',
            'door_code'=>'required',
            'birthday'=>'required',
            'live_people'=>'required',
            'live_info'=>'required',
            'live_type'=>'required',
            'old_type'=>'required',
            'fire_type'=>'required',
            'farm_num'=>'required',
            'farm_info'=>'required',
            'car_info'=>'required'
        ];
        $message = [
            'user_id.required' => '用户id不能为空',
            'leader.required' => '户主名称不能为空',
            'leader.max' => '户主名称长度不能超过240个字符',
            'province.required' => '请选择省份',
            'city.required' => '请选择城市',
            'district.required' => '请选择区',
            'street.required' => '请选择街道',
            'address.required' => '请输入街道、门牌号等信息',
            'address.max' => '街道、门牌号等信息长度不能超过100个字符',
            'idcard.required'=>'身份证号不能为空',
            'door_code.required'=>'门牌号不能为空',
            'birthday.required'=>'出生年月不能为空',
            'live_people.required'=>'居住人数不能为空',
            'live_info.required'=>'同住人信息不能为空',
            'live_type.required'=>'住户类型不能为空',
            'old_type.required'=>'老人类型不能为空',
            'fire_type.required'=>'燃气类型不能为空',
            'farm_num.required'=>'农田数不能为空',
            'farm_info.required'=>'牲畜情况不能为空',
            'car_info.required'=>'车辆情况不能为空'
        ];
        $validator = Validator::make($data,$rules,$message);
        if ($validator->fails()) {
            $error = $validator->errors()->first();
            return response()->json(['message' => $error,'code'=>400],200);
        }

        DB::beginTransaction();
        try {
            $user_id=$request->input('user_id');
            $com_id=User::where('id',$user_id)->first()->companyId;
            
            $company=[
                'comName' => $request->input("leader"),
                'leader' => $request->input("leader"),
                'province' => $request->input("province"),
                'city' => $request->input("city"),
                'district' => $request->input("district"),
                'street' => $request->input("street"),
                'community' => $request->input("community"),
                'address' => $request->input("address"),
                'area'=>$request->input("live_area"),
                'idcard' => $request->input("idcard")
            ];
            Company::where('id', $com_id)->update($company);

            $comuser=[
                'name'=>$company['leader'],
                'account'=>$company['idcard'],
                'province'=>$company['province'],
                'city'=> $company['city'],
                'district'=>$company['district'] ,
                'street'=>$company['street'] ,
                'community'=>$company['community']
            ];
            User::where('id', $user_id)->update($comuser);
            $resident=[
                'door_code'=>$request->input('door_code'),
                'birthday'=>$request->input('birthday'),
                'live_area'=>$request->input('live_area')??null,
                'live_people'=>$request->input('live_people'),
                'live_info'=>$request->input('live_info'),
                'live_type'=>$request->input('live_type'),
                'old_type'=>$request->input('old_type'),
                'fire_type'=>$request->input('fire_type'),
                'warm_type'=>$request->input('warm_type')??null,
                'alarm_type'=>$request->input('alarm_type')??null,
                'fire5_num1'=>$request->input('fire5_num1')??null,
                'fire5_num2'=>$request->input('fire5_num2')??null,
                'fire15_num1'=>$request->input('fire15_num1')??null,
                'fire15_num2'=>$request->input('fire15_num2')??null,
                'fire50_num1'=>$request->input('fire50_num1')??null,
                'fire50_num2'=>$request->input('fire50_num2')??null,
                'farm_num'=>$request->input('farm_num'),
                'farm_info'=>$request->input('farm_info'),
                'car_info'=>$request->input('car_info'),
                'note'=>$request->input('note')??''
            ];
            Resident::where('user_id', $user_id)->update($resident);
            DB::commit(); 
            return response()->json(['message'=>'修改成功','code' => 200], 200);
        } catch(Exception $e) {
            DB::rollBack();
            return response()->json(['message' =>$e->getMessage(),'code'=>400],200);
        }
    	
    }

}
